using AdminApi.Domain;
using Microsoft.EntityFrameworkCore;

namespace AdminApi.Repositories;

public class EfRepository<T> : IRepository<T> where T : EntityBase
{
    private readonly AdminDbContext _db;
    private DbSet<T> _tb;

    public EfRepository(AdminDbContext db)
    {
        _db = db;
        _tb = db.Set<T>();
    }

    public async Task<List<T>> GetAllAsync()
    {
        var list = _tb.ToListAsync();
        return await list;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        return await _tb.FindAsync(id);
    }

    public async Task<T> CreateAsync(T entity)
    {
        var list = _tb.Add(entity).Entity;
        await _db.SaveChangesAsync();
        return list;
    }

    public async Task<T> UpdateAsync(T entity)
    {
        _tb.Update(entity);
        await _db.SaveChangesAsync();

        return entity;
    }

    public async Task<T> DeleteAsync(T entity)
    {
        _tb.Remove(entity);
        await _db.SaveChangesAsync();

        return entity;
    }
}

